/*
	Copyright (c) 2010 <copyright holders>
	This source code is licensed under The MIT License,
	see the file LICENSE for details.
	*/

#include "SquadSelection.hpp"

#include "Faction.hpp"
#include "World.hpp"
#include "WorldManager.hpp"

namespace spelprog2 {
namespace presentation {

SquadSelections::SquadSelections(sim::WorldManager & worldMan, bool allowEnemy) :
    worldMan_(&worldMan),
    allowEnemy_(allowEnemy)
{
}

void SquadSelections::clear()
{
    selections_.clear();
}

bool SquadSelections::friendlySelected() const
{
    for (ConstIterator it = selections_.begin(), end = selections_.end(); it != end; ++it) {
        if (it->getPlayer() != worldMan_->getMyPlayerId()) {
            return false;
        }
    }

    return true;
}

bool SquadSelections::enemySelected() const
{
    for (ConstIterator it = selections_.begin(), end = selections_.end(); it != end; ++it) {
        if (it->getPlayer() == worldMan_->getMyPlayerId()) {
            return false;
        }
    }

    return true;
}

bool SquadSelections::add(const SquadSelection & sel)
{
    const bool isFriendly = sel.getPlayer() == worldMan_->getMyPlayerId();
    if (!selections_.empty()) {
        if (isFriendly != friendlySelected()) {
            return false;
        }
    }
    else {
        if (!isFriendly && !allowEnemy_) {
            return false;
        }
    }

    if (!worldMan_->getWorld().getFaction(sel.getPlayer()).hasSquad(sel.getSquad())) {
        return false;
    }
    if (selections_.find(sel) != selections_.end()) { //necessary as we want to return false on all non-changes
        return false;
    }

    selections_.insert(sel);
    return true;
}

bool SquadSelections::remove(const SquadSelection & sel)
{
    SelectionSet::iterator it = selections_.find(sel);
    if (it == selections_.end()) { //necessary as we want to return false on all non-changes
        return false;
    }

    selections_.erase(it);
    return true;
}

}; //presentation
}; //spelprog2
